<template>
  <el-form ref="formDiagRef" :model="user" :rules="rules" label-width="80px">
    <el-form-item label="旧密码" prop="oldPassword">
      <el-input v-model="user.oldPassword" placeholder="请输入旧密码" show-password type="password"/>
    </el-form-item>
    <el-form-item label="新密码" prop="newPassword">
      <el-input v-model="user.newPassword" placeholder="请输入新密码" show-password type="password"/>
    </el-form-item>
    <el-form-item label="确认密码" prop="confirmPassword">
      <el-input v-model="user.confirmPassword" placeholder="请确认新密码" show-password type="password"/>
    </el-form-item>
  </el-form>
  <el-form-item>
    <el-button type="primary" @click="submitOk">保存</el-button>
    <el-button type="danger" @click="close">关闭</el-button>
  </el-form-item>
</template>

<script lang="ts" setup>
import {updateUserPwd} from "@/api/system/user";
import {quantityPassword} from "@/utils/myRules"

const emits = defineEmits(['close'])

const props = defineProps({
  username: {
    type: String,
    default: ""
  }
})
const formDiagRef = ref()
const equalToPassword = (rule, value, callback) => {
  const pass = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,20}$/;
  if (value) {
    if (user.value.newPassword !== user.value.confirmPassword) {
      callback(new Error("两次输入的密码不一致"));
    } else if (!pass || value.length < 8) {
      callback(new Error("密码长度不能少于8位，必须含有大小写字母、特殊符号、数字"));
    } else {
      callback();
    }
  } else {
    callback("请输入您的密码");
  }
};

const rules = ref({
  oldPassword: [
    {required: true, message: "旧密码不能为空", trigger: "blur"}
  ],
  newPassword: [
    {required: true, validator: quantityPassword, trigger: "blur"},
  ],
  confirmPassword: [
    {required: true, validator: equalToPassword, trigger: "blur"}
  ]
})

const user = ref({
  oldPassword: undefined,
  newPassword: undefined,
  confirmPassword: undefined
})

function submitOk() {
  (formDiagRef.value as any).validate(valid => {
    if (valid) {
      updateUserPwd(user.value.oldPassword, user.value.newPassword, props.username).then(response => {
        ElMessage.success("修改成功");
        emits("close");
      });
    }
  });
}

function close() {
  user.value.oldPassword = ""
  user.value.newPassword = ""
  user.value.confirmPassword = ""
  emits("close");
}
</script>
